<template>
  <div>
    <el-button type="primary" @click="openAndFlashData">添加学生 <i class="el-icon-plus el-icon--right"></i>
    </el-button>

    <el-dialog title="添加学生" :visible.sync="dialogFormVisible" center>
      <div class="transfer-center">
        <el-transfer v-model="value" :data="transferData"></el-transfer>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false;addStudent()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {transferData} from "@/js/testConfig.mjs";
import axios from "axios";
import {Loading} from "element-ui";

export default {
  name: "AddStudentCard",
  data() {
    return {
      dialogFormVisible: false,
      sourceData: transferData.studentList,
      value: [],
      teacherId: this.$store.state.teacherId
    }
  },
  methods: {
    addStudent() {
      //todo 添加相对应的学生,并刷新数据流的状态
      if (this.value.length> 0) {
        console.log('格式化后的数据')
        console.log(this.formatSubmitData())
        axios
            .post(`teacher/selectStudentToManger`, this.formatSubmitData())
            .then(response => {
              console.log(response)
              this.flashData(this.teacherId)
              this.$store.dispatch("flashDataForTeacher_student")
            })
            .catch(e => {
              console.log(e)
            })
      }
      console.log('value中的数据')
      console.log(this.value)
      this.value=[]
    },
    //将数据转换为穿梭表的格式
    formatData() {
      const FormatList = []
      this.sourceData.forEach(item => {
        //用数据进行封装
        let data = {
          key: item.sid,
          label: item.name
        }
        FormatList.push(data)
      })
      return FormatList
    },
    formatSubmitData() {
      let sidList = []
      this.sourceData.forEach(item => {
        this.value.forEach(index => {
          if (index === item.sid) sidList.push(item.studentId)
        })
      })
      return {
        teacherId: this.teacherId,
        sidList: sidList
      }
    },
    openAndFlashData() {
      this.dialogFormVisible = true
      console.log('刷新数据流')
      this.flashData(this.teacherId)
    },
    flashData(id) {
      let loadingInstance = Loading.service({fullscreen: true});
      axios
          .get(`teacher/getNoSelectStudent/${id}`)
          .then(response => {
            console.log(response.data)
            this.sourceData = response.data
            loadingInstance.close()
          })
          .catch(e => {
            console.log(e)
          })
    }
  },
  computed: {
    transferData() {
      return this.formatData()
    }
  },
}
</script>

<style scoped>
</style>